package com.hxzy.shop.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.shop.commodity.mapper.DrugDetailsMapper;
import com.hxzy.shop.commodity.service.DrugDetailsService;
import com.hxzy.shop.entity.DrugDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author by zhy
 * @date 2021-07-12 16:19
 * @Version 1.0
 */
@Service
//todo:null
public class DrugDetailsServiceImpl extends ServiceImpl<DrugDetailsMapper, DrugDetails> implements DrugDetailsService {
    @Resource
    private DrugDetailsMapper detailsMapper;

    /**
     * 详细图保存
     *
     * @param drugUid             药品id
     * @param detailedDescription 详细图地址
     * @return 是否成功
     */
    @Override
    public boolean addDetails(Long drugUid, List<String> detailedDescription) {
        AtomicInteger size = new AtomicInteger();
        List<DrugDetails> collect = detailedDescription.stream().map(e -> new DrugDetails(drugUid, e, size.getAndIncrement())).collect(Collectors.toList());
        return this.saveBatch(collect);
    }

    /**
     * 根据id获得详细图
     *
     * @param id 药品的id
     * @return k 顺序，v url
     */
    @Override
    public Map<Integer, String> getDetails(Long id) {
        Map<Integer, String> map = new HashMap<>();
        List<DrugDetails> list = this.list(new LambdaQueryWrapper<DrugDetails>()
                .select(DrugDetails::getUrl, DrugDetails::getSort)
                .eq(DrugDetails::getDrugId, id)
        );
        list.forEach(e -> map.put(e.getSort(), e.getUrl()));
        return map;
    }

    /**
     * 药品详细图
     *
     * @param id            药品id
     * @param detailedImage 是否成功
     * @return 是否成功
     */
    @Override
    public boolean updateDetails(Long id, List<String> detailedImage) {
        Integer count = detailsMapper.selectCount(new LambdaQueryWrapper<DrugDetails>().eq(DrugDetails::getDrugId, id));
        if (count > 0) {
            boolean remove = this.remove(new LambdaQueryWrapper<DrugDetails>()
                    .eq(DrugDetails::getDrugId, id)
            );
            if (remove) {
                return addDetails(id, detailedImage);
            }
        } else if (count == 0) {
            return addDetails(id, detailedImage);
        }
        return false;
    }
}
